package se.slackers.sounder.algorithm;

public class GeneralGameOfLifeRule extends AbstractRule {
	private static final float DECREMENT = 0.1f;
	private final int[] birth;
	private final int[] survive;

	public GeneralGameOfLifeRule(final int[] birth, final int[] survive) {
		this.birth = birth;
		this.survive = survive;
	}

	@Override
	void step(final float[] source, final float[] dest, final int w, final int h) {
		int index = 0;
		for (int y = 0; y < h; y++) {
			for (int x = 0; x < w; x++) {
				int neighbours = 0;
				for (int dy = -1; dy <= 1; dy++) {
					for (int dx = -1; dx <= 1; dx++) {
						if (dx != 0 || dy != 0) {
							neighbours += get(source, x + dx, y + dy);
						}
					}
				}

				mrBox: do {
					if (get(source, x, y) == LIVE) {
						for (final int n : survive) {
							if (n == neighbours) {
								dest[index] = LIVE;
								break mrBox;
							}
						}
						dest[index] = Math.max(0, dest[index] - DECREMENT);
					} else {
						for (final int n : birth) {
							if (n == neighbours) {
								dest[index] = LIVE;
								break mrBox;
							}
						}
						dest[index] = Math.max(0, dest[index] - DECREMENT);
					}
				} while (false);

				index++;
			}
		}
	}
}
